package com.movieknight;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class SQLMoviesDataSource {
	// Database fields
	private SQLiteDatabase database;
	private MySQLiteHelper dbHelper;
	private String[] allColumns = { MySQLiteHelper.COLUMN_ID,
			MySQLiteHelper.COLUMN_MOVIE };

	public SQLMoviesDataSource(Context context) {
		dbHelper = new MySQLiteHelper(context);
	}

	public void open() throws SQLException {
		database = dbHelper.getWritableDatabase();
	}

	public void close() {
		dbHelper.close();
	}

	public SQLMovie createMovie(int movie) {
		ContentValues values = new ContentValues();
		values.put(MySQLiteHelper.COLUMN_MOVIE, movie);
		long insertId = database.insert(MySQLiteHelper.TABLE_MOVIES, null,
				values);
		Cursor cursor = database.query(MySQLiteHelper.TABLE_MOVIES,
				allColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null,
				null, null, null);
		cursor.moveToFirst();
		SQLMovie newMovie = cursorToMovie(cursor);
		cursor.close();
		return newMovie;
	}

	public void deleteMovie(SQLMovie movie) {
		long id = movie.getId();
		database.delete(MySQLiteHelper.TABLE_MOVIES, MySQLiteHelper.COLUMN_MOVIE + " = " + id, null);
	}

	public List<SQLMovie> getAllMovies() {
		List<SQLMovie> movies = new ArrayList<SQLMovie>();

		Cursor cursor = database.query(MySQLiteHelper.TABLE_MOVIES,
				allColumns, null, null, null, null, null);

		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			SQLMovie movie = cursorToMovie(cursor);
			movies.add(movie);
			cursor.moveToNext();
		}
		// Make sure to close the cursor
		cursor.close();
		return movies;
	}

	private SQLMovie cursorToMovie(Cursor cursor) {
		SQLMovie movie = new SQLMovie(cursor.getLong(0),cursor.getInt(1));
		//movie.setId(cursor.getLong(0));
		//movie.setMovie(cursor.getInt(1));
		return movie;
	}
}
